// page/admin/admin.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectArr: [],
    changeItem: {
      title: "",
      max: "",
      min: "",
      noPass: "",
      quantity: "",
      value: ""
    },
    selectId: '',
    openid: '',
    color: '60,150,220' //239,51,66
  },
  // 控制抽屉开关
  kindToggle: function (e) {
    var index = e.currentTarget.id, list = this.data.selectArr;
    var open = Boolean(list[index].open)
    if (list[index].edit) return false
    for (var i = 0; i < list.length; i++) {
      if (i == index) {
        list[i].open = !open
      } else if(Boolean(list[i].isAdd)) {
      } else {
        list[i].open = false
      }
    }
    this.setData({
      selectArr: list
    });
  },
  showEdit(event) {
    let index = event.target.dataset.index, list = this.data.selectArr
    let selectId = list[index]._id
    if(Boolean(list[index].isAdd)){
      this.add(index)
    }else{
      var changeObj = {}
      var item = this.data.changeItem
      for(var key in item){
        if(Boolean(item[key])){
          changeObj[key] = item[key]
        }
      }
      if(JSON.stringify(changeObj) == "{}"){
        list[index].edit = !Boolean(list[index].edit)
        this.setData({ selectArr: list, selectId: selectId })
      }else{
        this.update(changeObj,selectId)
      }
    }
  },
  inputChange(event) {
    let key = event.target.dataset.key,
      index =  event.target.dataset.index,
      changeValue = event.detail.value,
      selectArr = this.data.selectArr,
      item = this.data.changeItem
    if(Boolean(selectArr[index].isAdd)){
      selectArr[index][key] = changeValue
      this.setData({
        selectArr: selectArr
      })
    }else{
      item[key] = changeValue
      this.setData({
        changeItem: item
      })
    }
  },
  update(changeObj,selectId){
    wx.showLoading({
      title: '',
    })
    const db = wx.cloud.database()
    db.collection('selectArr').doc(selectId).update({
      data: {
        ...changeObj
      },
      success: res => {
        var selectArr = this.data.selectArr
        var index = ''
        for(var i=0;i<selectArr.length;i++){
          if(selectArr[i]._id == selectId){
            index = i
            break;
          }
        }
        selectArr[index].edit = false
        for(var key in changeObj){
          selectArr[index][key] = changeObj[key]
        }
        this.setData({
          selectArr: selectArr,
          changeItem:{
            title: "",
            max: "",
            min: "",
            noPass: "",
            quantity: "",
            value: ""
          }
        },()=>{
          wx.hideLoading()
          wx.showToast({
            title: '修改成功',
          })
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '修改失败',
        })
      }
    })
  },
  showDelete(event) {
    let index = event.target.dataset.index, list = this.data.selectArr
    let selectId = list[index]._id
    let _this = this;
    this.setData({ selectId: selectId })
    wx.showModal({
      title: '温馨提示',
      content: '确认删除本条数据吗？',
      cancelText: '我再想想',
      confirmColor: _this.colorRGBtoHex(`rgb(${this.data.color})`),
      confirmText: '删除',
      success(res) {
        if (res.confirm) {
          _this.delete()
        }
      }
    })
  },
  delete() {
    let selectId = this.data.selectId
    let selectArr = this.data.selectArr
    let _this = this
    if(Boolean(selectArr[0].isAdd)){
      selectArr.splice(0, 1)
      _this.setData({
        selectId: '',
        selectArr: selectArr
      })
      return false
    }
    wx.showLoading({
      title: '',
    })
    const db = wx.cloud.database()
    db.collection('selectArr').doc(selectId).remove({
      success: res => {
        for(var i=0;i<selectArr.length;i++){
          if(selectArr[i]._id==selectId){
            selectArr.splice(i,1)
            break; 
          }
        }
        wx.showToast({
          title: '删除成功',
        })
        _this.setData({
          selectId: '',
          selectArr: selectArr
        },()=>{
          wx.hideLoading()
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '删除失败',
        })
      }
    })
  },
  addItem(){
    var selectArr = this.data.selectArr
    if(selectArr.length>0&&Boolean(selectArr[0].isAdd)){
      return wx.showToast({
        icon: 'none',
        title: '不同同时新增多条数据',
      })  
    }
    var item = JSON.parse(JSON.stringify(this.data.changeItem))
    item.min = 1; item.open = true; item.edit = true; item.isAdd = true
    selectArr.unshift(item)
    this.setData({selectArr:selectArr})
  },
  add(index){
    var selectArr = this.data.selectArr
    var item = selectArr[index]
    if(!(item.max&&item.noPass&&item.title&&item.quantity&&item.value))
      return wx.showToast({
        icon: 'none',
        title: '新增数据不完整',
      })  
      wx.showLoading({
        title: '',
      })
    const db = wx.cloud.database()
    db.collection('selectArr').add({
      data: {
        max: item.max,
        min: 1,
        noPass: item.noPass,
        quantity: item.quantity,
        title: item.title,
        value: item.value
      },
      success: res => {
        item.isAdd = false
        item.edit = false
        wx.showToast({
          title: '新增成功',
        })
        this.setData({
          selectArr:selectArr
        },()=>{
          wx.hideLoading()
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '新增失败'
        })
      }
    })
  },
  getData() {
    wx.showLoading({
      title: '',
    })
    const db = wx.cloud.database()
    // 查询当前用户所有的 counters
    db.collection('selectArr').where({
      //_openid: this.data.openid
    }).get({
      success: res => {
        let selectArr = res.data.reverse()
        this.setData({
          selectArr: selectArr
        }, () => {
          wx.hideNavigationBarLoading()
          wx.stopPullDownRefresh()
          wx.hideLoading()
        })
      },
      fail: err => {
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh()
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
      }
    })
  },
  colorRGBtoHex(color) {
    var rgb = color.split(',');
    var r = parseInt(rgb[0].split('(')[1]);
    var g = parseInt(rgb[1]);
    var b = parseInt(rgb[2].split(')')[0]);
    var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    return hex;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.openid) { // 获取openid 
      this.setData({
        openid: app.globalData.openid
      })
    }
    this.getData()
    wx.setNavigationBarColor({//设置导航栏颜色
      frontColor: '#ffffff',
      backgroundColor: this.colorRGBtoHex(`rgb(${this.data.color})`)
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})